package com.example.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.utils.R;
import com.example.gulimall.cart.feign.ProductFeignService;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.vo.Cart;
import com.example.gulimall.cart.vo.CartItem;
import com.example.gulimall.cart.vo.SkuInfoVo;
import com.example.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREIFX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        Object o = cartOps.get(skuId.toString());
        if(o == null){
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                // 1 查询商品信息
                R info = productFeignService.info(skuId);
                SkuInfoVo data = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                // 2.商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setCount(num);
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(data.getSkuId());
            }, executor);


            // 3.查询组合信息
            CompletableFuture<Void> getSaleAttr = CompletableFuture.runAsync(() -> {
                // 1 查询商品信息
                List<String> info = productFeignService.getSkuSaleAttrValues(skuId);

                // 2.新商品添加到购物车
                cartItem.setSkuAttr(info);
            }, executor);

            CompletableFuture.allOf(getSaleAttr,getSkuInfo).get();

            //往redis里放商品数据
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }else{
            CartItem cartItem = JSON.parseObject((String) o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(o, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();

        if(userInfoTo.getUserId() == null){
            // 临时用户
            String cartKey = CART_PREIFX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else{
            String cartKey = CART_PREIFX + userInfoTo.getUserId();
            // 如果临时购物车不为空 则需要合并
            List<CartItem> cartItems = getCartItems(CART_PREIFX + userInfoTo.getUserKey());
            if(cartItems != null && cartItems.size() > 0){
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
                clearCart(CART_PREIFX + userInfoTo.getUserKey());
            }
            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
        }

        return cart;
    }

    // 获取购物车
    public BoundHashOperations<String, Object, Object> getCartOps() {
        // 用户类型 是否登录(每次filter拦截的时候会查你的线程)
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartkey;
        if(userInfoTo.getUserId()!=null){
            // 登陆
            cartkey = CART_PREIFX + userInfoTo.getUserId().toString();
        }else{
            cartkey = CART_PREIFX + userInfoTo.getUserKey();
        }

        // 为redis的key绑定增删改查
        BoundHashOperations<String, Object, Object> hashOps = template.boundHashOps(cartkey);

        return hashOps;
    }

    public List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> cartOps = template.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0){
            List<CartItem> collect = values.stream().map((value) -> {
                String string = (String) value;
                CartItem object = JSON.parseObject(string, CartItem.class);
                return object;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey){
        template.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String string = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),string);
    }

    @Override
    public void countItem(Long skuId, Integer count) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        String string = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),string);
    }

    @Override
    public void delItem(Long deleteId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(deleteId.toString());
    }

    @Override
    public List<CartItem> getCurrentCartItems() {

        UserInfoTo infoTo = CartInterceptor.threadLocal.get();
        if (infoTo.getUserId() == null){
            //没登陆
            return null;
        }else{
            String cartKey = CART_PREIFX + infoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> items = cartItems.stream().filter(CartItem::getCheck)
                    .map(item->{
                        // 更新最新价格
                        R price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(new BigDecimal(price.get("data").toString()));
                        return item;
                    })
                    .collect(Collectors.toList());
            return items;
        }
    }
}
